package managedbeans;

import entities.Authorisation;
import entities.Forumposts;
import entities.Forumthreads;
import java.util.ArrayList;
import java.util.Collections;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ValueChangeEvent;
import langresources.ResourcesController;
import utils.dataaccess.DBInterface;


@ManagedBean(name="forumPostsBean")
@SessionScoped
public class ForumPostsBean extends GenericForumBean{

    private ArrayList<Forumposts> posts;
    private String text;
    private Forumthreads selectedThread;
    private double rate;

    public ForumPostsBean() {
         currentThread = getCurrentThread();
         currentBlock  = getCurrentBlock();
         DBInterface.updateEventCounter();
    }

    public ArrayList<Forumposts> getPosts() {
        ArrayList<Forumposts> currentPostList = DBInterface.getPosts(getCurrentThread());
        Collections.sort(currentPostList);
        return  currentPostList;
    }

    public String leaveComment(Authorisation user){
        
        if(user==null){
            showMessage(ResourcesController.extractResource("MESSAGE.ACCESS_DENIED"), ResourcesController.extractResource("USER_NOT_AUTHORIZED"));
        } else {
            Forumposts newPost = new Forumposts();
            newPost.setAuthor(user.getUsername());
            newPost.setRate(0d);
            newPost.setText(text);
            newPost.setTid((int)currentThread.getId());
            newPost.setDatetime(getTimestamp());
            newPost.setId(generateID());

            currentThread = getCurrentThread();
            currentBlock  = getCurrentBlock();

            DBInterface.save(newPost);
            text = "";
        }
        return "/post.xhtml?faces-redirect=true";
    }

    public void handleRate(ValueChangeEvent evt){
        rate = (Double)evt.getNewValue();
    }

    public void updateRate(Forumposts post){
        post.setRate((post.getRate()+rate)/2);
        DBInterface.persist(post);
    }

    public String deleteComment(Forumposts post){
        DBInterface.delete(post);
        showMessage(ResourcesController.extractResource("MESSAGE.INFO"), ResourcesController.extractResource("POST_REMOVED")+" #"+post.getId());
        return "/faces/post.xhtml";
    }


    // GETTERS-SETTERS

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Forumthreads getSelectedThread() {
        return selectedThread;
    }

    public void setSelectedThread(Forumthreads selectedThread) {
        this.selectedThread = selectedThread;
    }

    public void setPosts(ArrayList<Forumposts> posts) {
        this.posts = posts;
    }

    public double getRate() {
        return rate;
    }

    public void setRate(double rate) {
        this.rate = rate;
    }


}
